/*
 * @Author: Collin colin.w.cai@hotmail.com
 * @Date: 2022-07-16 20:47:53
 * @LastEditors: Collin colin.w.cai@hotmail.com
 * @LastEditTime: 2022-12-03 22:02:52
 * @FilePath: /linn-go-practice/mysql/dbConnect.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package xxorm

import (
	"fmt"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"xorm.io/core"

	"practices/xxorm/model"
)

// 加 * 表示是值应用方式，而非引用地址
var engine *xorm.Engine

func init() {
	engine = CreateEngine()
}

// create engine of xorm
func CreateEngine() *xorm.Engine {
	var err error
	engine, err = xorm.NewEngine("mysql", "root:123456@tcp(192.168.31.119:33306)/collin-database?charset-utf8")
	//设置本地化信息
	engine.TZLocation, _ = time.LoadLocation("Asia/Shanghai")
	//SnakeMapper 支持struct为驼峰式命名，表结构为下划线命名之间的转换，这个是默认的Maper；
	engine.SetColumnMapper(core.SnakeMapper{})
	engine.Logger().ShowSQL(true)
	engine.Logger().SetLevel(core.LOG_DEBUG)

	if err != nil {
		panic(err)
	} else {
		engine.Ping()
	}
	return engine
}

// create engine of xorm
func CreateEngineByConfig(config string) *xorm.Engine {
	var err error
	engine, err = xorm.NewEngine("mysql", config)
	if err != nil {
		fmt.Printf("err.Error(): %v\n", err.Error())
	}
	return engine
}

func GetEmployeeById(employeeId int32) model.Employee {

	employee := model.Employee{EmployeeId: employeeId}
	exist, err := engine.ID(employeeId).Get(&employee)
	if err != nil {
		fmt.Printf("err.Error(): %v\n", err.Error())
	}

	if exist {
		return employee
	}

	return employee
}

func GetEmployees() []model.Employee {
	var employees []model.Employee
	err := engine.Find(&employees)
	if err != nil {
		fmt.Printf("err.Error(): %v\n", err.Error())
	}

	return employees
}

func GetEmployeesBySQL() []model.Employee {
	var employees []model.Employee
	err := engine.SQL("select * from employee where name LIKE 'coll%'").Find(&employees)
	if err != nil {
		fmt.Printf("err.Error(): %v\n", err.Error())
	}
	return employees
}

func GetCountOfemployee() int64 {
	employee := new(model.Employee)
	total, err := engine.Where("1 = 1").Count(employee)
	if err != nil {
		fmt.Printf("err.Error(): %v\n", err.Error())
	}

	return total
}

func CreateEmployee(employee model.Employee) {
	_, err := engine.Insert(&employee)
	if err != nil {
		fmt.Printf("err.Error(): %v\n", err.Error())
	}
}

func UpdateEmployee(employee model.Employee) {
	_, err := engine.ID(employee.EmployeeId).Update(&employee)
	if err != nil {
		fmt.Printf("err.Error(): %v\n", err.Error())
	}
}

func DeleteEmployee(employeeId int32) {
	_, err := engine.ID(employeeId).Delete(&model.Employee{})
	if err != nil {
		fmt.Printf("err.Error(): %v\n", err.Error())
	}
}
